package com.iemes.service.impl.workcenter_model;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.iemes.entity.NumberRuleFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.base.BaseMapper;
import com.iemes.service.workcenter_model.NumberRuleService;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ShiroSecurityHelper;
import com.iemes.util.UUIDUtils;

@Service
public class NumberRuleServiceImpl implements NumberRuleService {
	@Inject
	private BaseMapper baseMapper;

	private Logger log = Logger.getLogger(this.getClass());
	
	private static NumberRuleFormMap numberRuleFormMapAfterHandle = new NumberRuleFormMap();
	
	public static NumberRuleFormMap GetNumberRuleFormMapAfterHandle(){	
		return numberRuleFormMapAfterHandle;
	}

	@Override
	@Transactional
	public void saveNumberRule(NumberRuleFormMap numberRuleFormMap) throws BusinessException {
		try {
			String id = numberRuleFormMap.getStr("id");
			String numberRule = numberRuleFormMap.getStr("number_rule");
			
			if(StringUtils.isEmpty(numberRule)) {
				throw new BusinessException("编号规则不能为空，请输入！");
			}
			
			// 编号生成规则:【前缀】+【时间戳(精确到秒)】+【数字(按规则增长,且每秒数字都从起点开始计数)】+【后缀】
			// 整个编号长度为固定
			// 增加卡控 前缀和后缀的总长度不能超过整个编号长度-时间戳长度-6
			int totalNumberLen = 32;
		    Object obOl= numberRuleFormMap.get("order_length");
		    totalNumberLen = Integer.valueOf(obOl.toString());
			int numberTimestampLen = "19990101121212".length();
			String prefix = numberRuleFormMap.getStr("prefix");
			String postfix = numberRuleFormMap.getStr("postfix");
			int fixLen = (StringUtils.isEmpty(prefix) ? 0 : prefix.length())
					+ (StringUtils.isEmpty(postfix) ? 0 : postfix.length());
			int maxFixLen = totalNumberLen - numberTimestampLen - 6;
			if (fixLen > maxFixLen) {
				throw new BusinessException("编号前缀和后缀的总长度不能超过！" + maxFixLen);
			}
			
			NumberRuleFormMap numberRuleFormMap2 = new NumberRuleFormMap();
			numberRuleFormMap2.put("site_id", ShiroSecurityHelper.getSiteId());
			numberRuleFormMap2.put("number_rule", numberRule);
			List<NumberRuleFormMap> listNumberRuleFormMap = baseMapper.findByNames(numberRuleFormMap2);
			
			//如果编号存在，就执行更新，不存在就执行新增
			if (ListUtils.isNotNull(listNumberRuleFormMap)) {
				//更新 
				NumberRuleFormMap numberRuleFormMap3 = new NumberRuleFormMap();
				numberRuleFormMap3 = listNumberRuleFormMap.get(0);
				id = numberRuleFormMap3.getStr("id");
				numberRuleFormMap.set("id", id);
				
				baseMapper.editEntity(numberRuleFormMap);
			}else {
				//新增
				id = UUIDUtils.getUUID();
				numberRuleFormMap.set("id", id);
				baseMapper.addEntity(numberRuleFormMap);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("编号规则保存失败！" + e.getMessage());
		}
	}

	@Override
	@Transactional
	public void delNumberRule(String numberRuleId) throws BusinessException {
		try { // 删除编号规则
			NumberRuleFormMap numberRuleFormMap = new NumberRuleFormMap();
			numberRuleFormMap.put("id", numberRuleId);
			baseMapper.deleteByNames(numberRuleFormMap);

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("编码规则删除失败！" + e.getMessage());
		}

	}
	
	@Override
	@Transactional
	public List<String> generateNumberByNumberRule(NumberRuleFormMap numberRuleFormMap, int numberCounts,boolean isUpdateSeedNumber)
			throws BusinessException {
		try {
			List<String> listNumber = new ArrayList<String>();
			String numberRuleId = numberRuleFormMap.getStr("id");
			if (StringUtils.isEmpty(numberRuleId)) {
				throw new BusinessException("编号规则ID为空！");
			}
			NumberRuleFormMap numberRuleFormMap2 = new NumberRuleFormMap();
			//numberRuleFormMap2.put("site_id", ShiroSecurityHelper.getSiteId());
			//numberRuleFormMap2.put("number_type", numberType);
			//numberRuleFormMap2.put("where"," where site_id = '"+ ShiroSecurityHelper.getSiteId() +"' and number_type='"+ numberType +"'");
			numberRuleFormMap2.put("id", numberRuleId);
			List<NumberRuleFormMap> listNumberRuleFormMap = baseMapper.findByNames(numberRuleFormMap2);
			if (ListUtils.isNotNull(listNumberRuleFormMap)) {
				numberRuleFormMap = listNumberRuleFormMap.get(0);
			} else {
				throw new BusinessException("编号规则ID" + numberRuleId + "的编号规则不存在！");
			}

			// 根据编号规则和需要的编号数量生成编号
			// 编号生成规则:【前缀】+【时间戳(精确到秒)】+【数字(按规则增长,且每秒数字都从起点开始计数)】+【后缀】
			int totalNumberLen = 32;
			Object obOl = numberRuleFormMap.get("order_length");
			totalNumberLen = Integer.valueOf(obOl.toString());

			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			Date now = new Date();
			String timestampStr = sdf.format(now);
			int timestampLen = timestampStr.length();

			String prefix = numberRuleFormMap.getStr("prefix");
			prefix = StringUtils.isEmpty(prefix) ? "" : prefix;
			String postfix = numberRuleFormMap.getStr("postfix");
			postfix = StringUtils.isEmpty(postfix) ? "" : postfix;
			
			int fixLen = (StringUtils.isEmpty(prefix) ? 0 : prefix.length())
					+ (StringUtils.isEmpty(postfix) ? 0 : postfix.length());

			int digitsLen = totalNumberLen - timestampLen - fixLen;
			int currentSeed = 0;
			Date lastGenerateNumberTime = numberRuleFormMap.getDate("last_generate_number_time");
			if(lastGenerateNumberTime == null) {
				lastGenerateNumberTime = now;
			}
			long diffSeconds = (now.getTime() - lastGenerateNumberTime.getTime()) / 1000;
			if (diffSeconds > 0) {
				// 如果当前时间不在上次生成编号的秒数内，则当前种子数从基数开始，否则当前种子数继续增长
				currentSeed = numberRuleFormMap.getInt("base_number");
			} else {
				currentSeed = numberRuleFormMap.getInt("current_number");
			}
			int increment = numberRuleFormMap.getInt("increment");
			{
				for (int i = 0; i < numberCounts; i++) {
					currentSeed = currentSeed + increment;
					if (digitsLen > 0) {
						if (String.valueOf(currentSeed).length() > digitsLen) {
							// 如果数字的位数不足以放下所有增长的序号，则抛出异常
							throw new BusinessException("数字序号的长度超出了限制" + digitsLen + "，请联系系统管理员！");
						}
						String numberStr = String.format("%0" + digitsLen + "d", currentSeed);
						String totalNumber = prefix + timestampStr + numberStr + postfix;
						listNumber.add(totalNumber);
					}
				}
				numberRuleFormMap.set("current_number", currentSeed);
				numberRuleFormMap.set("last_generate_number_time", DateUtils.getStringDateTime());
			}
			numberRuleFormMapAfterHandle = numberRuleFormMap;
			if(isUpdateSeedNumber) {
				baseMapper.editEntity(numberRuleFormMap);
			}
			
			return listNumber;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("编号生成失败！" + e.getMessage());
		}
	}

}
